package org.yuanqiframework.yuanqi.core.utils.dict;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Map;

@Slf4j
@Component
public class WebDictionary implements ApplicationContextAware {

    private final Object lock = new Object();

    private volatile boolean flag = true;

    private synchronized void init(Class<?> c) {
        if (!flag) {
            return;
        }
        Field[] fields = c.getFields();
        for (Field field : fields) {
            String fn = field.getName().toLowerCase();
            DictField dictField = field.getAnnotation(DictField.class);
            if (dictField != null) {
                boolean autoGroupAndLabelFromField = dictField.autoGroupAndLabelFromField();

                String label = dictField.label();
                if ("".equals(label)) {
                    label = dictField.value();
                }
                if ("".equals(label)) {
                    label = fn.substring(fn.lastIndexOf("_") + 1);
                }
                String group = dictField.group();
                String key = dictField.key();
                if ("".equals(group) && "".equals(key)) {
                    autoGroupAndLabelFromField = true;
                }

                if (autoGroupAndLabelFromField) {
                    if (!fn.contains("_")) {
                        log.error("dictField autoGroupAndLabelFromField error, field name must contain _");
                    }
                    String k = null;
                    try {
                        k = (String) field.get(c);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                    DictUtils.group(fn.substring(0, fn.lastIndexOf("_")))
                            .put(k, label);
                } else {
                    DictUtils.group(group)
                            .put(key, label);
                }
            }
        }
        log.info("Init WebDictionary {}", c);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(DictClass.class);
        synchronized (lock) {
            beansWithAnnotation.values().forEach(bean -> {
                init(bean.getClass());
            });
            flag = false;
        }
    }
}
